package com.example.demo.dao;

import com.example.demo.dto.Empoyee;
import com.example.demo.dto.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class EmpolyeeMapper {

    @Autowired
    LogMapper logMapper;

    private static Map<Integer, Empoyee> empoyeeMap = null;

    private Integer id = 106;

    static {
        empoyeeMap = new HashMap<>();
        empoyeeMap.put(101, new Empoyee(101, "李天", 101));
        empoyeeMap.put(102, new Empoyee(102, "李乐", 102));
        empoyeeMap.put(103, new Empoyee(103, "李男", 103));
        empoyeeMap.put(104, new Empoyee(104, "李书", 104));
        empoyeeMap.put(105, new Empoyee(105, "李高", 105));
    }

    public Collection<Empoyee> getEmpoleeData() {
        return empoyeeMap.values();
    }

    public Empoyee getById(Integer id) {
        return empoyeeMap.get(id);
    }

    public String insert(Empoyee empoyee) {
        try{
            Integer curId = id++;
            empoyee.setId(curId);
            empoyeeMap.put(curId, empoyee);
            log("数据插入", curId);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据存储异常";
        }
    }

    public String insetBatch(List<Empoyee> empoyees) {
        try {
            empoyees.forEach(item -> {
                Integer curId = id++;
                item.setId(curId);
                empoyeeMap.put(curId, item);
                log("数据批量插入", curId);
            });
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据批量存储异常";
        }
    }

    public String updateData(Empoyee empoyee) {
        try {
            Integer id = empoyee.getId();
            empoyeeMap.remove(id);
            empoyeeMap.put(id, empoyee);
            log("数据更新", id);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据更新异常";
        }
    }

    public String deleteById(Integer id) {
        try {
            empoyeeMap.remove(id);
            log("数据删除", id);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据删除异常";
        }
    }

    private void log(String operateType, Integer id) {
        Log log = new Log();
        log.setDataOrigin("员工信息");
        log.setOperateType(operateType);
        log.setOriginId(id);
        logMapper.insert(log);
    }
}
